package com.monolithiot.sso.controller.device;

import com.monolithiot.sso.common.context.Constants;
import com.monolithiot.sso.common.entity.DeviceAuthorization;
import com.monolithiot.sso.common.entity.User;
import com.monolithiot.sso.common.exception.AlreadyExistedException;
import com.monolithiot.sso.common.vo.BasicJsonResponse;
import com.monolithiot.sso.service.DeviceAuthorizationService;
import com.monolithiot.sso.service.DeviceTypeService;
import com.monolithiot.sso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 2018/12/22 Create by 郭文梁
 * DeviceUserController
 * 设备端用户相关访问控制器
 *
 * @author 郭文梁
 * @date 2018/12/22
 */
@RestController
@RequestMapping("/device/user")
public class DeviceUserController {
    private final UserService userService;
    private final DeviceAuthorizationService deviceAuthorizationService;
    private final DeviceTypeService deviceTypeService;

    @Autowired
    public DeviceUserController(UserService userService, DeviceAuthorizationService deviceAuthorizationService, DeviceTypeService deviceTypeService) {
        this.userService = userService;
        this.deviceAuthorizationService = deviceAuthorizationService;
        this.deviceTypeService = deviceTypeService;
    }

    /**
     * 用户登录
     *
     * @param account    账户
     * @param password   密码
     * @param deviceType 设备类型
     * @return BJR with DeviceAuthorization entity
     */
    @PostMapping("/{deviceType}/_login")
    public BasicJsonResponse<DeviceAuthorization> login(@PathVariable("deviceType") Integer deviceType,
                                                        @RequestParam("account") String account,
                                                        @RequestParam("password") String password,
                                                        @RequestParam("serialNumber") String serialNumber) {

        if (!deviceTypeService.exists(deviceType)) {
            return BasicJsonResponse.paramError("设备类型不存在");
        }

        User user = userService.login(account, password);
        if (user == null) {
            return BasicJsonResponse.paramError("用户名或密码错误");
        }
        DeviceAuthorization authorization = deviceAuthorizationService
                .auth(user, Constants.Auth.DEFAULT_DEVICE_AUTHORIZATION_EXPIRE_IN, deviceType, serialNumber);
        return BasicJsonResponse.ok(authorization);
    }

    /**
     * 为设备授权设置名称
     *
     * @param token 令牌
     * @param name  名称
     * @return BJR with DeviceAuthorization Entity
     */
    @PostMapping("/_set-name")
    public BasicJsonResponse<DeviceAuthorization> setName(@RequestParam("token") String token,
                                                          @RequestParam("name") String name) {
        DeviceAuthorization authorization = deviceAuthorizationService.setName(token, name);
        if (authorization == null) {
            return BasicJsonResponse.paramError("令牌无效");
        }
        return BasicJsonResponse.ok(authorization);
    }

    /**
     * 通过用户查找已授权的设备
     *
     * @param userId 用户ID
     * @return BJR with authorization list
     */
    @GetMapping("/find-by-user")
    public BasicJsonResponse<List<DeviceAuthorization>> findByUser(
            @RequestParam("userId") Integer userId) {
        User user = userService.get(userId);
        if (user == null) {
            return BasicJsonResponse.paramError("用户不存在");
        }
        List<DeviceAuthorization> authorizations = deviceAuthorizationService.findByUser(user);
        return BasicJsonResponse.ok(authorizations);
    }

    /**
     * 用户注册
     *
     * @param user          用户对象(name, password , mobileNumber必填)
     * @param smsVerifyCode 短信验证码
     * @return BJR with user entity
     */
    @PostMapping("/_register")
    public BasicJsonResponse<User> register(User user, @RequestParam("smsVerifyCode") String smsVerifyCode) {
        try {
            @NotNull User res = userService.register(user);
            return BasicJsonResponse.ok(res);
        } catch (AlreadyExistedException e) {
            return BasicJsonResponse.paramError("用户已存在" + e.getMessage());
        }
    }
}
